package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import objects.Board;
import objects.Character;
import objects.HypoResult;
import objects.Player;
import objects.Room;
import objects.Weapon;
import utils.FactoryUI;
import bl.GameManager;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class Action
 */
@WebServlet(name = "Action", urlPatterns =
{
    "/Action"
})
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// Set the content to be JSON, as it is a very easy way to pass several parameters in JS.
		// Every consequence the user might run into in the code is labeled in a specific code
		// so the web UI will react accordingly. (the "res" parameter of the json)
		response.setContentType("application/json");
	    response.setCharacterEncoding("UTF-8");
		String strRoom = request.getParameter("room");
		String strWeap = request.getParameter("weapon");
		String strChar = request.getParameter("character");
		
		PrintWriter out = response.getWriter();
		
		String choice = request.getParameter("checked");
		
		// if the user chose to accuse:
		if (choice.equals("accuse"))
		{
			Room rmRoom = Room.valueOf(strRoom); 
			Weapon wpnWeap = Weapon.valueOf(strWeap);
			Character chrChar = Character.valueOf(strChar);
			
			boolean bDidWin = GameManager.winOrLose(rmRoom, chrChar, wpnWeap);
			
			String accusation = "\nThe accusation: " + chrChar.name() + " in the " + rmRoom.name() + " with the " + wpnWeap + ".";
			
			// If the user won in the accusation, then he's a winner.
			if (bDidWin)
			{
				ResultJson rs = new ResultJson();
				rs.res = "3";
				String strRes = new Gson().toJson(rs);
				out.print(strRes);
				String playerName = Board.getInstance().getCurrPlayerInstance().getPlayerName();
				JsonObject jsAction = new JsonObject();
				jsAction.addProperty("code", "win");
				jsAction.addProperty("playerName", playerName);
				jsAction.addProperty("message", "Player " +playerName+ " Is the winner!");
				Board.getInstance().addJsActions(jsAction);
				
			}
			// Otherwise, the user is disqualified and removed from the game.
			else
			{
				Board.getInstance().getCurrPlayerInstance().setInTheGame(false);
				Board.getInstance().getCurrPlayerInstance().setReason("disqualified");
				ResultJson rs = new ResultJson();
				
				boolean onePlayerLeft = Board.getInstance().onePlayerLeft();
				
				if (Board.getInstance().getNumberOfHumansInGame() == 0)
				{
					onePlayerLeft = true;
				}
				
				String strRes = new Gson().toJson(rs);
				out.print(strRes);
				String playerName = Board.getInstance().getCurrPlayerInstance().getPlayerName();
				JsonObject jsAction = new JsonObject();
				jsAction.addProperty("code", "disqualified");
				jsAction.addProperty("player", playerName);
				jsAction.addProperty("hasMorePlayers", !onePlayerLeft);
				jsAction.addProperty("message", "Player " +playerName+ " chose the accuse and was wrong so he is out of the game! " + accusation);
				Board.getInstance().addJsActions(jsAction);
			}
		}
		// if the user chose to assume:
		if (choice.equals("assume"))
		{
			Room rmRoom = Room.valueOf(strRoom);
			Weapon wpnWeap = Weapon.valueOf(strWeap);
			Character chrChar = Character.valueOf(strChar);
			// Get the result of the hypothesis into hr. (Contains a list of contradicting cards and a cont. player.)
			HypoResult hr = GameManager.makehypothesis(rmRoom, chrChar, wpnWeap);
			
			String assumption = "\nThe assumption: " + chrChar.name() + " in the " + rmRoom.name() + " with the " + wpnWeap + ".";
			
			// If any cont. player showed any cards
			if (hr.getCards() != null)
			{
				// If the list of cards is of size 1, do not prompt user to choose a card.
				if(hr.getCards().size() == 1)
				{
					ResultJson rs = new ResultJson();
					rs.res = "1";
					rs.content = FactoryUI.getShowedContradictHtml(hr.getCards().get(0),hr.getContPlayer().getPlayerName());
					rs.countCard = hr.getCards().size();
					String strRes = new Gson().toJson(rs);
					out.print(strRes);
					
					String playerName = Board.getInstance().getCurrPlayerInstance().getPlayerName();
					JsonObject jsAction = new JsonObject();
					jsAction.addProperty("code", "assumeOneCardRes");
					jsAction.addProperty("player", playerName);
					jsAction.addProperty("content", rs.content);
					jsAction.addProperty("contPlayer", hr.getContPlayer().getPlayerName());
					jsAction.addProperty("contCard", hr.getCards().get(0).getName());
					jsAction.addProperty("message", "Player " +playerName+ " made an assumption and was contradicted by "
											+ hr.getContPlayer().getPlayerName()  + "! " + assumption);
					Board.getInstance().addJsActions(jsAction);
				}
				// if it is bigger, prompt user for card choice.
				else if (hr.getCards().size() > 1)
				{
					ResultJson rs = new ResultJson();
					rs.res = "1";
					rs.content = FactoryUI.getChooseContradictHtml(hr.getCards(),hr.getContPlayer().getPlayerName());
					rs.countCard = hr.getCards().size();
					String strRes = new Gson().toJson(rs);
					
					out.print(strRes);
					
					String playerName = Board.getInstance().getCurrPlayerInstance().getPlayerName();
					JsonObject jsAction = new JsonObject();
					jsAction.addProperty("code", "assumeManyCardsRes");
					jsAction.addProperty("player", playerName);
					jsAction.addProperty("content", rs.content);
					jsAction.addProperty("contPlayer", hr.getContPlayer().getPlayerName());
					jsAction.addProperty("message", "Player " +playerName+ " made an assumption and was contradicted by " + hr.getContPlayer().getPlayerName() + "! " + assumption);
					Board.getInstance().addJsActions(jsAction);
				}
				else
				{
					ResultJson rs = new ResultJson();
					rs.res = "2";
					rs.content = "";
					String strRes = new Gson().toJson(rs);
					out.print(strRes);
					
					String playerName = Board.getInstance().getCurrPlayerInstance().getPlayerName();
					JsonObject jsAction = new JsonObject();
					jsAction.addProperty("code", "assumeNoRes");
					jsAction.addProperty("player", playerName);
					jsAction.addProperty("message", "Player " +playerName+ " made an assumption and was not contradicted by anyone! " + assumption);
					Board.getInstance().addJsActions(jsAction);
				}
			}
		}
		
	}

	@SuppressWarnings("unused")
	// Inner class used to deserialize json into info
    private class ResultJson {
		private String res;
        private String content;
        private int	   countCard;
        private boolean onePlayerLeft;
        private String playerList;
    }   
    
}
